package com.hhz.springcloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 自定义过滤
 *
 * @Author Rem
 * @Date 2020-03-13
 * @Version 1.0
 */


@Component
public class GlobleFilter implements GlobalFilter, Ordered {


    /**
     * http://localhost:9527/payment/findById/3?uname=tt
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("全局过滤~~~" + new Date());
        ServerHttpRequest request = exchange.getRequest();
        //定义过滤条件uname
        String uname = request.getQueryParams().getFirst("uname");
        if (uname == null) {
            System.err.println("用户名为空~~");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    /**
     * 过滤优先级 0表示最高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
